package com.iotimc.attendancesystem.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.event.AttendanceEvent;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author david
 * @date 2017/3/27
 */

public class InputNumLayout extends LinearLayout {
    private EditText editText;

    public void setEditText(EditText editText) {
        this.editText = editText;
    }

    public InputNumLayout(Context context) {
        super(context);
    }

    public InputNumLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_num_input, this, true);
        ButterKnife.bind(view, this);
    }


    @OnClick({R.id.one, R.id.two, R.id.three, R.id.four, R.id.five,
            R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.zero,
            R.id.del, R.id.clear})
    public void onClick(View view) {
        EventBus.getDefault().post(new AttendanceEvent(true));
        if (editText == null) {
            return;
        }
        int index = editText.getSelectionStart();
        Editable editable = editText.getText();
        switch (view.getId()) {
            case R.id.one:
                editable.insert(index, "1");
                break;
            case R.id.two:
                editable.insert(index, "2");
                break;
            case R.id.three:
                editable.insert(index, "3");
                break;
            case R.id.four:
                editable.insert(index, "4");
                break;
            case R.id.five:
                editable.insert(index, "5");
                break;
            case R.id.six:
                editable.insert(index, "6");
                break;
            case R.id.seven:
                editable.insert(index, "7");
                break;
            case R.id.eight:
                editable.insert(index, "8");
                break;
            case R.id.nine:
                editable.insert(index, "9");
                break;
            case R.id.zero:
                editable.insert(index, "0");
                break;
            case R.id.clear:
                editText.setText("");
                break;
            case R.id.del:
                String str = editText.getText().toString();
                if (!TextUtils.isEmpty(str) && index != 0) {
                    editable.delete(index - 1, index);
                }
                break;
            default:
                break;
        }
    }
}
